<template>
  <div class="container">
    <sq-header :selected="1"></sq-header>

    <div class="course-page">
      <img :src="courseDetail.imgUrl" alt="" class="course-bg-img">
      <div class="course-page-footer">
        <div class="course-page-footer-up">
          <div class="course-page-footer-title">{{courseDetail.name}}</div>
          <div class="course-page-footer-author">
            <img :src="courseDetail.authorImgUrl">
            <div>{{courseDetail.authorName}}</div>
          </div>
        </div>
        <div class="course-page-footer-down">
          <div class="course-page-footer-desc">{{courseDetail.briefDesc}}</div>
          <div class="course-page-footer-source">来源：{{courseDetail.sourceName}}</div>
        </div>
      </div>
    </div>

    <sq-sticky>
      <mt-navbar v-model="selectedTab" class="sq-navbar">
        <mt-tab-item id="10" @click.native="scollToDesc">简介</mt-tab-item>
        <mt-tab-item id="20" @click.native="scollToAudios">节目</mt-tab-item>
        <mt-tab-item id="30" @click.native="scollToBuyinfo">购买须知</mt-tab-item>
      </mt-navbar>
    </sq-sticky>

    <div class="sq-navbar-content" id="sq-navbar-content-div">
      <section class="content-desc" id="sq-content-desc-section">
        <p class="stress">课程简介:</p>
        <div>
          {{courseDetail.detailDesc}}
          </div>
      </section>
      <section class="content-audios" id="sq-content-audios-section">
        <ul class="content-audios-box">
          <sq-audio-item v-for="(item, index) in courseAudios" :item="item" :key="item.id" @togglePlay="togglePlay(item)"></sq-audio-item>
        </ul>
      </section>
      <section class="content-buyinfo" id="sq-content-buyinfo-section">
        <p class="stress">购买须知:</p>
        <div>
          {{courseDetail.buyNote}}
          </div>
      </section>
      <section class="content-customer" id="sq-content-customer-section">
        <p class="stress">联系客服:</p>
        <div>
          这里是联系客服，这里是联系客服，这里是联系客服，这里是联系客服，
          这里是联系客服，这里是联系客服，这里是联系客服，这里是联系客服，
          这里是联系客服，这里是联系客服，这里是联系客服，这里是联系客服，
        </div>
        <div>
          QQ: 819729209
        </div>
        <div>
          TEL: 11011011011
        </div>
      </section>
    </div>
    <div class="sq-footer" v-if="!courseDetail.hasBuy">
      <button class="sq-footer-try-free" @click="tryListenFree()">免费试听</button>
      <button class="sq-footer-buy" @click="buyCourse(courseDetail.id)">订阅课程（¥{{courseDetail.discPrice|priceFormat}}）</button>
    </div>

    <sq-goto-top-button />
  </div>
</template>

<script>

  import Vue from 'vue'
  import SqHeader from '../components/Header'
  import AudioItem from '../components/AudioItem'
  import Sticky from '../components/Sticky'
  import GotoTopButton from '../components/GotoTopButton'
  import { Navbar, TabItem, TabContainer, TabContainerItem} from 'mint-ui'
  import { getCourseDetail, getCourseByCategory, getCourseAudios} from '../api/index'
  import { mapGetters } from 'vuex';
  Vue.component(SqHeader.name, SqHeader);
  Vue.component(AudioItem.name, AudioItem);
  Vue.component(Navbar.name, Navbar);
  Vue.component(Sticky.name, Sticky);
  Vue.component(GotoTopButton.name, GotoTopButton);
  Vue.component(TabItem.name, TabItem);
  Vue.component(TabContainer.name, TabContainer);
  Vue.component(TabContainerItem.name, TabContainerItem);


  export default {
    name: 'Course',
    data () {
      return {
        selectedTab: "10",
        courseDetail: {},
        courseAudios: []
      }
    },
    created () {
      this.refreshData();
    },
    computed: {
      ...mapGetters([
        'islogin',
        'playingAudioItem'
      ])
    },
    watch: {
      courseDetail: function() {
        this.updateContentMargin();
      },
      islogin: function(){
        this.refreshData();
      }
    },
    methods: {
      refreshData() {
        var that = this;
        const reg = /\/(category|course)\/(\d*)$/
        if (reg.test(this.$route.path)) {
          const type = RegExp.$1;
          const ID = RegExp.$2;
          if (type === 'category') {
            getCourseByCategory(ID).then(function(resp){
              that.courseDetail = resp.data;
              console.log("/course/" + that.courseDetail.id + "/" + that.courseDetail.randId + "?categoryID=" + ID);
              window._hmt.push(['_trackPageview', '/course/' + that.courseDetail.id + "/" + that.courseDetail.randId + "?categoryID=" + ID]);
              getCourseAudios(that.courseDetail.id).then(function(resp){
                that.courseAudios = resp.data;
              }).catch(function(err){
                console.log(err);
              });

            }).catch(function(err){
              console.log(err);
            });
          } else {
            getCourseDetail(ID).then(function(resp){
              that.courseDetail = resp.data;
              getCourseAudios(that.courseDetail.id).then(function(resp){
                that.courseAudios = resp.data;
              }).catch(function(err){
                console.log(err);
              });
            }).catch(function(err){
              console.log(err);
            });
          }
        }
      },
      updateContentMargin() {
        var contentElement = window.document.getElementById('sq-navbar-content-div');
        if(!contentElement){
          return;
        }
        var showBuyBar = !this.courseDetail.hasBuy;
        if(showBuyBar) {
          contentElement.style.marginBottom = '44px';
          this.$store.dispatch("toggleBuyBarItem", {
            showBuyBar: true
          });
        } else{
          contentElement.style.marginBottom = '0px';
          this.$store.dispatch("toggleBuyBarItem", {
            showBuyBar: false
          });
        }
      },
      buyCourse(courseId) {
        var islogin = this.$store.getters.islogin;
        if(!islogin) {
          window._hmt.push(['_trackEvent', '订单', '登录', '课程号：' + courseId]);
          this.$store.dispatch("toggleLoginBox");
          return;
        }
        window._hmt.push(['_trackEvent', '订单', '确认', '课程号：' + courseId]);
        this.$router.push({ name: 'Buy', params: { id: courseId }});
      },
      togglePlay(audioItem) {
        audioItem.hasListen = 1;
        this.$store.dispatch("togglePlayAudioItem", {
          playingAudioItem: audioItem,
          playingCourseAudios: this.courseAudios
        });
      },
      tryListenFree() {
        var len = this.courseAudios.length;
        for(var i=0; i<len; i++){
          var audioItem = this.courseAudios[i];
          if(audioItem.free){
            this.togglePlay(audioItem);
            break;
          }
        }
      },
      _scrollToElement(elementId, selectedTab){
        var element = window.document.getElementById(elementId);
        //获取相对位置
        var relateY = element.getBoundingClientRect().top;
        var scrollY = window.document.documentElement.scrollTop || window.document.body.scrollTop;
        // 44 是tabbar 占的高度 +1 是滚动不是很精确，可能看到边框
        var absoluteY = relateY + scrollY - 44 + 1;
        window.document.body.scrollTop = absoluteY;
        window.document.documentElement.scrollTop = absoluteY;
        // 设置滚动以后，handleScroll 更新的selectedTab可能与预期不一致
        var that = this;
        setTimeout(function(){
          that.selectedTab = selectedTab;
        }, 0);
      },
      scollToDesc() {
        this._scrollToElement('sq-content-desc-section', '10');
      },
      scollToAudios() {
        this._scrollToElement('sq-content-audios-section', '20');
      },
      scollToBuyinfo() {
        this._scrollToElement('sq-content-buyinfo-section', '30');
      },
      _reachBottom(){
        var scrollY = window.document.documentElement.scrollTop || window.document.body.scrollTop;
        var windowHeight = window.document.documentElement.clientHeight || window.document.body.clientHeight;
        var totalHeight = window.document.documentElement.scrollHeight || window.document.body.scrollHeight;
        if( totalHeight - (windowHeight + scrollY) < 100 ){
          return true;
        }
        return false;
      },
      handleScroll() {
        var audiosElement = window.document.getElementById('sq-content-audios-section');
        var buyinfoElement = window.document.getElementById('sq-content-buyinfo-section');
        // 购买须知滚动到顶部或滚动到底部了，tab显示【购买须知】
        // 网页高度不够，购买须知可能触及不到顶部，所以添加_reachBottom判断
        if(buyinfoElement.getBoundingClientRect().top <= 45
          || this._reachBottom() ){
          this.selectedTab = "30";
        }else if(audiosElement.getBoundingClientRect().top <= 45 ){
          this.selectedTab = "20";
        }else {
          this.selectedTab = "10";
        }
      }
    },
    mounted() {
      window.addEventListener('scroll', this.handleScroll);
    },
    destroyed() {
      this.$store.dispatch("toggleBuyBarItem", {
        showBuyBar: false
      });
      window.removeEventListener('scroll', this.handleScroll);
    }
  }
</script>

<style>
  div.sq-navbar {
    background-color: #f6f6f6;
    height: 44px;
    border-bottom: 1px solid #cccccc;
  }

  div.sq-navbar .mint-tab-item-label {
    font-size: 16px;
    line-height: 22px;
  }
  div.sq-navbar .mint-tab-item.is-selected {
    border-bottom: 2px solid #3385ff;
    color: #3385ff;
    margin-bottom: 0;
  }
  div.sq-navbar .mint-tab-item {
    padding: 11px 0px;
  }
</style>
<!-- custom scoped component -->
<style scoped>

  .container{
    width: 100%;
    height: 100%;
    margin: 0px;
    padding: 0px;
  }

  .course-page {
    height: 70vw;
    position: relative;
  }

  @media screen and (min-width: 769px) {
    .course-page {
      height: 300px;
    }
  }

  .course-bg-img {
    width: 100%;
    height: 100%;
  }

  .course-page-footer {
    position: absolute;
    bottom: 0px;
    left: 0px;
    width: 100%;
    height: 63px;
    background-color: rgba(0, 0, 0, 0.5);
    overflow:hidden;
    display: flex;
    flex-direction: column;
  }
  .course-page-footer-up {
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 10px;
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    margin-top: 8px;
    font-weight: bolder;
    color: #fff;
    min-width: 0px;
  }

  .course-page-footer-title {
    white-space:nowrap;
    text-overflow:ellipsis;
    overflow: hidden;
  }

  .course-page-footer-author {
    display: flex;
    flex: 0 0 auto;
  }

  .course-page-footer-author img {
    width: 27px;
    height: 27px;
    border-radius: 13.5px;
    margin-right: 5px;
  }

  .course-page-footer-down {
    display: flex;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 10px;
    font-size: 12px;
    margin-bottom: 8px;
    color: #ccc;
    min-width: 0px;
  }

  .course-page-footer-desc {
    white-space:nowrap;
    text-overflow:ellipsis;
    overflow: hidden;
  }

  .course-page-footer-source {
    flex: 0 0 auto;
  }


  .sq-navbar-content section:not(:last-child) {
    border-bottom: 12px solid #f6f6f6;
  }

  .content-desc,.content-buyinfo,.content-customer {
    text-align: left;
    padding-left: 12px;
    font-size: 14px;
    line-height: 21px;
    color: #000000;
  }

  .content-audios ul {
    margin: 0px;
    padding: 0px;
  }

  .stress {
    font-weight: bolder;
    margin: 0px;
    padding-top: 20px;
    text-align: left;
    font-size: 16px;
  }

  /* course content container */
  .sq-footer {
    position: fixed;
    left: 0px;
    bottom: 0px;
    height: 44px;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }

  .sq-footer button {
    height: 100%;
    border: 0px;
  }

  .sq-footer-try-free {
    flex-grow: 1;
    background-color: #ffffff;
    color: #02adea;
    width: 33%;
  }

  .sq-footer-buy {
    flex-grow: 2;
    background-color: #fe6b40;
    color: #ffffff;
    width: 67%;
  }

</style>
